# -*- coding: utf-8 -*-
from application import app, db
from flask import Blueprint, request, make_response, redirect
from common.libs.Helper import ops_renderJSON, ops_renderErrJSON, ops_render
from common.libs.DataHelper import getCurrentTime, getCurrentDate
from common.libs.Helper import unduplicate, handle_data, datetimetran, getage, dingtalkpost
from common.models.user import User
from common.models.department import Department
from common.models.user_change import UserChange
from common.models.user_eduexp import UserEduexp
from common.models.user_workexp import UserWorkexp
from common.models.user_family import UserFamily
from common.models.user_tag import UserTag
from common.models.user_post import UserPost
from common.models.keymap import Keymap
from common.models.user_weight import UserWeight
from common.models.user_resign import UserResign
from common.models.weight import Weight
from common.models.user_commission import UserCommission
from sqlalchemy import and_, or_
from common.libs.SQLTransform import queryToDict
from dingtalk import SecretClient, model
import json, requests
from config.dingtalk_setting import AppKey, AppSecret, AgentId, role_hr, bpmid
import os
import sys
from werkzeug.utils import secure_filename
import urllib.parse
import ast
import pandas as pd
import datacompy
from sqlalchemy import desc

##连接
client = SecretClient(AppKey, AppSecret)  # 新 access_token 获取方式

member_page = Blueprint("member_page", __name__)


# 钉钉登录
@member_page.route("/ddlogin")
def ddlogin():
    authCode = request.args.get('code')

    token_params = {
        'appkey': AppKey,
        'appsecret': AppSecret,
    }
    dd_token = 'https://oapi.dingtalk.com/gettoken'
    token_response = requests.get(dd_token, params=token_params)  # 向API发起GET请求
    tokenData = token_response.json()
    access_token = tokenData['access_token']

    userid_params = {
        "code": authCode,
    }
    dd_userid = 'https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=' + access_token
    userid_response = requests.post(dd_userid, params=userid_params)  # 向API发起GET请求
    useridData = userid_response.json()

    result = useridData['result']
    name = result['name']
    userid = result['userid']
    user = User.query.filter_by(userid=userid).first()
    if user:
        id = user.id
        roleid = user.role

    else:
        id = 6666
        roleid = 1

    userinfo = client.user.get(userid)
    avatar = userinfo['avatar']

    return json.dumps(
        {"code": 200, "msg": "登录成功", "name": name, "userid": userid, "avatar": avatar, "id": id, "roleid": roleid},
        indent=4,
        sort_keys=True,
        default=str,
        ensure_ascii=False)


@member_page.route('/getalluser', methods=['GET', 'POST'])
def getAllUser():
    selecarr = request.json.get('selecarr')
    roleid = request.json.get('roleid')

    weight = Weight.query.filter_by(roleid=roleid).first()
    hrrange = weight.hrrange.split(',')

    member = User.query.order_by(User.id).filter(User.depid.in_(selecarr)).filter(
        User.hrrange.in_(hrrange)).filter(
        or_(User.status == 4, User.status == 1)).all()
    rts = []
    for item in member:
        # age = getage(item.idcardnum)
        temp = dict(id=item.id, name=item.name, sex=item.sex, department=item.department.name, post=item.post,
                    contract_body=item.contract_body,
                    mobile=item.mobile, email=item.email, workplace=item.workplace,
                    idcardnum=item.idcardnum, address=item.address,
                    political=item.political, nation=item.nation,
                    workdate=str(item.workdate), jiguan=item.jiguan, idcardaddress=item.idcardaddress, title=item.title,
                    pq=item.pq,
                    employdate=str(item.employdate), inductiondate=str(item.inductiondate),
                    hobby=item.hobby, tall=item.tall, weight=item.weight, blood=item.blood, ecname=item.ecname,
                    ec=item.ec,
                    ecmobile=item.ecmobile)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getuserdetail', methods=['GET', 'POST'])
def getuserdetail():
    id = request.args.get('id')

    member = User.query.filter_by(id=id).all()
    eduexp = UserEduexp.query.filter_by(userid=id).all()
    workexp = UserWorkexp.query.filter_by(userid=id).all()
    family = UserFamily.query.filter_by(userid=id).all()
    change = UserChange.query.filter_by(userid=id).all()
    commission = UserCommission.query.filter_by(userid=id).all()

    member2 = User.query.filter_by(id=id).first()

    if member2.dingtalkdepid != None:
        dingtalkdeplist = member2.dingtalkdepid.split(',')
    else:
        dingtalkdeplist = None
        # print("没有部门")

    eduexpinfo = []
    for item in eduexp:
        temp = dict(id=item.id, name=item.name, degree=item.degree, major=item.major, stime=str(item.stime),
                    etime=str(item.etime), education=item.education, educationtype=item.educationtype,
                    educationsn=item.educationsn,
                    degreesn=item.degreesn
                    )
        eduexpinfo.append(temp)

    workexpinfo = []
    for item in workexp:
        temp = dict(id=item.id, name=item.name, post=item.post, stime=str(item.stime),
                    etime=str(item.etime)
                    )
        workexpinfo.append(temp)

    familyinfo = []
    for item in family:
        temp = dict(id=item.id, relationship=item.relationship, post=item.post, mobile=item.mobile,
                    company=item.company, name=item.name
                    )
        familyinfo.append(temp)

    changeinfo = []
    for item in change:
        temp = dict(id=item.id, bdep=item.bdep.name, adep=item.adep.name, bpost=item.bpost, apost=item.apost,
                    changedate=str(item.changedate)[0:10]
                    )
        changeinfo.append(temp)

    commissioninfo = []
    for item in commission:
        temp = dict(id=item.id, post=item.post, content=item.content, sn=item.sn, stime=str(item.stime)[0:10],
                    etime=str(item.etime)[0:10]
                    )
        commissioninfo.append(temp)

    memberinfo = queryToDict(member)

    manager = "无"
    highdepartment = "无"

    dep = Department.query.filter_by(id=memberinfo[0]["depid"]).first()
    if dep.mannger == id:
        highdep = Department.query.filter_by(id=dep.pid).first()
        if highdep:
            highdepartment = highdep.name
            manageruser = User.query.filter_by(id=highdep.mannger).first()
            if manageruser:
                manager = manageruser.name
    else:
        manageruser = User.query.filter_by(id=dep.mannger).first()
        manager = manageruser.name

    if member2.idcardnum:
        age = getage(member2.idcardnum)
        memberinfo[0]["age"] = age

    res = {"eduexp": eduexpinfo, "workexp": workexpinfo, "member": memberinfo, "family": familyinfo,
           "change": changeinfo, "commission": commissioninfo,
           "dingtalkdeplist": dingtalkdeplist, "manager": manager, "highdepartment": highdepartment}
    return json.dumps(res, ensure_ascii=False)


@member_page.route('/getuserbystatus', methods=['GET', 'POST'])
def getuserbystatus():
    status = request.json.get('status')
    member = User.query.order_by(User.created_time.desc()).filter_by(status=status).all()
    rts = []
    for item in member:
        temp = dict(id=item.id, name=item.name, department=item.department.name, userid=item.userid,
                    email=item.email, sex=item.sex, mobile=item.mobile, post=item.post, employdate=str(item.employdate))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getemployuser', methods=['GET', 'POST'])
def getEmployUser():
    member = User.query.order_by(User.id.desc()).filter_by(status=4).all()
    rts = []
    for item in member:
        long, years, month = handle_data(str(item.employdate))
        longnum = years * 12 + month
        if longnum >= 3:
            temp = dict(id=item.id, name=item.name, department=item.department.name,
                        email=item.email, sex=item.sex, mobile=item.mobile, long=long, employdate=str(item.employdate),
                        post=item.post)
            rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getdepartment', methods=['GET', 'POST'])
def getDepartment():
    department = Department.query.order_by(Department.id.asc()).all()
    rts = []
    for item in department:
        temp = dict(id=item.id, pid=item.pid, label=item.name, strid=str(item.id))
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getpost', methods=['GET', 'POST'])
def getPost():
    post = UserPost.query.all()
    rts = []
    for item in post:
        temp = dict(value=item.name, label=item.name, key=item.id)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getweight', methods=['GET', 'POST'])
def getweight():
    weight = Weight.query.all()
    rts = []
    for item in weight:
        temp = dict(id=item.id, value=item.roleid, label=item.hrname)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/usersearch', methods=['GET', 'POST'])
def usersearch():
    name = request.json.get('name')
    sdate = request.json.get('sdate')
    edate = request.json.get('edate')
    sex = request.json.get('sex')
    if sdate == "" or edate == "":
        sdate = "1000-01-01"
        edate = "3000-01-01"
    sage = request.json.get('sage')
    eage = request.json.get('eage')

    if name != "":
        member = User.query.filter(
            or_(User.status == 4, User.status == 1)).filter(
            or_(*[User.name.like('%' + name + '%')]))
    else:
        member = User.query.order_by(User.created_time.desc()).filter(
            or_(User.status == 4, User.status == 1)).all()
    rts = []

    for item in member:
        temp = dict(id=item.id, name=item.name, department=item.department.name,
                    email=item.email, sex=item.sex, mobile=item.mobile, post=item.post,
                    idcardnum=item.idcardnum, address=item.address,
                    workplace=item.workplace)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getdepname', methods=['GET', 'POST'])
def getdepname():
    id = request.args.get('id')
    department = Department.query.filter_by(id=id).first()
    name = department.name
    return json.dumps(name, ensure_ascii=False)


@member_page.route('/getusername', methods=['GET', 'POST'])
def getusername():
    id = request.args.get('id')
    user = User.query.filter_by(id=id).first()
    name = user.name
    return json.dumps(name, ensure_ascii=False)


# 实时模糊搜索人员
@member_page.route('/getuserinfobynamelike', methods=['GET', 'POST'])
def getUserInfoByNameLike():
    name = request.args.get('name')
    member = User.query.filter(User.name.like('%' + name + '%')).all()
    rts = []
    for item in member:
        temp = dict(label=str(item.name) + "(" + str(item.id) + ")", value=item.userid, key=item.id)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/getuserinfobyuserid', methods=['GET', 'POST'])
def getUserInfoByUserid():
    userid = request.args.get('userid')
    member = User.query.filter_by(userid=userid).first()
    name = ""
    if member:
        name = member.name
    return json.dumps(name, ensure_ascii=False)


# 获得用户标签
@member_page.route('/getusertag', methods=['GET', 'POST'])
def getUserTag():
    type = request.args.get('type')
    tag = UserTag.query.filter_by(type=type).all()
    rts = []

    for item in tag:
        temp = dict(value=item.id, label=item.name)
        rts.append(temp)

    return json.dumps(rts, ensure_ascii=False)


# @member_page.route('/synuserinfo', methods=['GET', 'POST'])
# def synuserinfo():
#     # 获取钉钉用户列表
#     dingtalkUser = []
#     dp = client.department.list(fetch_child=True)
#     for i in dp:
#         users = client.user.get_dept_member(i["id"])
#         for u in users:
#             user_info = client.user.get(u)
#             temp = dict(userid=user_info["userid"], name=user_info["name"], mobile=user_info["mobile"],
#                         department=user_info["department"], )
#             dingtalkUser.append(temp)
#
#     # 获取系统用户列表
#     member = User.query.filter(
#         or_(User.status == 4, User.status == 1)).all()
#     AdamUser = []
#     for item in member:
#         dingtalkdeplist = item.dingtalkdepid.split(',')
#         temp = dict(userid=item.userid, name=item.name, department=dingtalkdeplist, mobile=item.mobile,
#                     jobnumber=str(item.id))
#         AdamUser.append(temp)
#
#     # 提取用户id
#     dingtalkUser_id = set(temp['userid'] for temp in dingtalkUser)
#     AdamUser_id = set(temp['userid'] for temp in AdamUser)
#     # 寻找差异，建立新增用户数组与删除用户数组
#     add_user = list(temp['userid'] for temp in AdamUser if temp['userid'] not in dingtalkUser_id)
#     delete_user = list(temp['userid'] for temp in dingtalkUser if temp['userid'] not in AdamUser_id)
#
#     # 筛选需新增的用户信息并添加
#     for i in add_user:
#         userinfo = list(filter(lambda x: x['userid'] == i, AdamUser))
#         a = client.user.create(userinfo[0])
#         print(a)
#
#     for i in delete_user:
#         b = client.user.delete(i)
#         print(b)
#
#     # 将用户信息列表转化为DataFrame
#     dingtalkUserPd = pd.DataFrame(dingtalkUser, columns=['userid', 'name', 'department', 'mobile'])
#     AdamUserUserPd = pd.DataFrame(AdamUser, columns=['userid', 'name', 'department', 'mobile'])
#
#     # 设置主键
#     dingtalkUserPd.set_index('userid', inplace=True)
#     AdamUserUserPd.set_index('userid', inplace=True)
#
#     # 比较两个表
#     compy = datacompy.Compare(dingtalkUserPd, AdamUserUserPd, on_index=True)
#
#     # # 需删除的index
#     delete_user_list = compy.df1_unq_rows.to_dict('split')["index"]
#     print(delete_user_list)
#     # 需新增的index
#     add_user_list = compy.df2_unq_rows.to_dict('split')["index"]
#     print(add_user_list)
#     # 需更新的index
#     update_user_list = compy.all_mismatch().to_dict('split')["index"]
#     syninfo = []
#     # 新增
#     if add_user_list != []:
#         for i in add_user_list:
#             userinfo = list(filter(lambda x: x['jobnumber'] == i, AdamUser))
#             a = client.user.create(userinfo[0])
#             temp = dict(name=userinfo[0]["name"], id=userinfo[0]["jobnumber"], action="新增")
#             syninfo.append(temp)
#
#     # 删除
#     if delete_user_list != []:
#         for i in delete_user_list:
#             userinfo = list(filter(lambda x: x['userid'] == i, dingtalkUser))
#             b = client.user.delete(i)
#             temp = dict(name=userinfo[0]["name"], id=userinfo[0]["userid"], action="删除")
#             syninfo.append(temp)
#
#     # 更新
#     if update_user_list != []:
#         for i in update_user_list:
#             userinfo = list(filter(lambda x: x['userid'] == i, AdamUser))
#             print(userinfo)
#             c = client.user.update(userinfo[0])
#             temp = dict(name=userinfo[0]["name"], id=userinfo[0]["userid"], action="修改")
#             syninfo.append(temp)
#
#     return json.dumps(syninfo, ensure_ascii=False)


# ----------------------------------入转调离----------------------------------------

# 发起入职(前)
@member_page.route('/postadd', methods=['GET', 'POST'])
def postadd():
    newdata = request.json.get("userinfo")
    user = User.query.filter_by(id=newdata['id']).first()
    user.depid = newdata['depid']
    if newdata['workdate'] != '':
        user.workdate = newdata['workdate']
    user.depid = newdata['depid']
    user.post = newdata['post']
    if newdata['employdate'] != '':
        user.employdate = newdata['employdate']
    if newdata['contract_start'] != '':
        user.contract_start = newdata['contract_start']
    if newdata['contract_end'] != '':
        user.contract_end = newdata['contract_end']
    user.contract_long = newdata['contract_long']
    user.contract_body = newdata['contract_body']
    user.contract_type = newdata['contract_type']
    user.workplace = newdata['workplace']
    user.isss = newdata['isss']
    user.hrrange = newdata['hrrange']
    user.status = 4
    db.session.commit()

    dep = newdata['depid']

    userinfo = {"userid": user.userid, "dept_id_list": dep, "job_number": user.userid}
    url = 'https://oapi.dingtalk.com/topapi/v2/user/update'
    res = dingtalkpost(url, userinfo)

    return json.dumps("入职成功,信息已更新", ensure_ascii=False)


# 转正(后)
@member_page.route('/employuser', methods=['GET', 'POST'])
def employuser():
    res = request.values.to_dict()
    processInstanceId = res['processInstanceId']
    content = {
        "process_instance_id": processInstanceId
    }
    url = "https://oapi.dingtalk.com/topapi/processinstance/get"
    bpminfo = dingtalkpost(url=url, content=content)
    content = bpminfo['process_instance']['form_component_values']
    userid = content[1]['value']

    user = User.query.filter_by(id=userid).first()
    user.status = 1
    user.inductiondate = getCurrentDate()
    db.session.commit()

    print("人员转正流程")

    return json.dumps("info", ensure_ascii=False)


# 调岗(前)
@member_page.route('/sendchangepost', methods=['GET', 'POST'])
def sendchangepost():
    form = request.json.get('form')
    hrid = request.json.get('posterid')
    userid = request.json.get('userid')
    fileinfo = request.json.get("fileinfo")

    hrinfo = client.user.get(hrid)

    user = User.query.filter_by(userid=userid).first()

    # department = Department.query.filter_by(id=form["depid"]).first()

    form_component_values = [
        {
            'name': '工号', 'value': user.id
        },
        {
            'name': '调岗人员', 'value': user.name
        },
        {
            'name': '生效日期', 'value': str(form["date"])[:10]
        },
        {
            'name': '调出部门', 'value': [user.depid]
        },
        {
            'name': '原岗位', 'value': user.post
        },
        {
            'name': '调入部门', 'value': [form["depid"]]
        },
        {
            'name': '调整后岗位', 'value': form["post"]
        },
        {
            'name': '备注', 'value': form["bz"]
        },
        {
            "name": "附件",
            "value": fileinfo
        },
    ]

    process_code = bpmid["调岗流程"]
    dept_id = hrinfo["department"][0]

    dingtalksn = client.bpms.processinstance_create(agent_id=AgentId, form_component_values=form_component_values,
                                                    process_code=process_code, originator_user_id=hrid,
                                                    dept_id=dept_id)

    return json.dumps("调岗流程发起成功", ensure_ascii=False)


# 调岗(后)
@member_page.route('/changeuser', methods=['GET', 'POST'])
def changeuser():
    res = request.values.to_dict()
    processInstanceId = res['processInstanceId']
    content = {
        "process_instance_id": processInstanceId
    }
    url = "https://oapi.dingtalk.com/topapi/processinstance/get"
    bpminfo = dingtalkpost(url=url, content=content)

    # bpminfo = client.bpms.processinstance_get(processInstanceId)
    content = bpminfo['process_instance']['form_component_values']
    taskinfo = bpminfo['process_instance']['tasks']
    posterid = taskinfo[0]['userid']
    posterlist = posterid.split("。")

    userid = content[1]['value']
    changedate = content[2]['value']
    bdepname = content[3]['value']
    bdep = Department.query.filter_by(name=bdepname).first()
    bdepid = bdep.id
    adepname = content[5]['value']
    adep = Department.query.filter_by(name=adepname).first()
    adepid = adep.id
    bpost = content[4]['value']
    apost = content[6]['value']
    bz = content[7]['value']

    user = User.query.filter_by(id=userid).first()
    name = user.name
    user.depid = adepid
    user.post = apost
    db.session.commit()

    change = UserChange()
    change.userid = userid
    change.changedate = changedate
    change.bdepid = bdepid
    change.adepid = adepid
    change.bpost = bpost
    change.apost = apost
    change.bz = bz
    change.bpmid = processInstanceId

    change.updated_time = change.created_time = getCurrentTime()
    db.session.add(change)
    db.session.commit()

    userinfo = {"userid": user.userid, "dept_id_list": adepid, }
    url = 'https://oapi.dingtalk.com/topapi/v2/user/update'
    res = dingtalkpost(url, userinfo)

    msg = {
        "msgtype": "text",
        "text": {
            "content": "【" + name + "】的调岗流程已审批完毕，人员信息库数据已更新"
        }
    }
    postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=posterlist)

    print("岗位调整流程")

    return json.dumps("info", ensure_ascii=False)


# 辞职(后)
@member_page.route('/resignuser', methods=['GET', 'POST'])
def resignuser():
    res = request.values.to_dict()
    processInstanceId = res['processInstanceId']
    content = {
        "process_instance_id": processInstanceId
    }
    url = "https://oapi.dingtalk.com/topapi/processinstance/get"
    bpminfo = dingtalkpost(url=url, content=content)
    content = bpminfo['process_instance']['form_component_values']
    userid = content[2]['value']
    resigndate = content[6]['value']

    user = User.query.filter_by(id=userid).first()
    user.status = 0
    db.session.commit()

    resign = UserResign()
    resign.userid = userid
    resign.resigndate = resigndate
    resign.bpmid = processInstanceId
    resign.created_time = resign.updated_time = getCurrentTime()
    db.session.add(resign)
    db.session.commit()

    userinfo = {
        "userid": user.userid
    }
    url = 'https://oapi.dingtalk.com/topapi/v2/user/delete'
    res = dingtalkpost(url, userinfo)

    print("人员辞职流程")

    return json.dumps("info", ensure_ascii=False)


# ----------------------------------入转调离----------------------------------------

# 删除人员
@member_page.route('/deleteuser', methods=['GET', 'POST'])
def deleteuser():
    id = request.args.get("id")
    user = User.query.filter_by(id=id).first()
    user.status = 0
    db.session.commit()

    return json.dumps("删除成功", ensure_ascii=False)


# ----------------------------------用户信息维护----------------------------------------


@member_page.route("/imgupload", methods=['GET', 'POST'])
def imgupload():
    userid = request.form.get("userid")
    f = request.files.getlist('files')[0]
    print(f)
    filename = str(userid) + ".png"

    basepath = os.path.dirname(sys.path[0])  # 当前文件所在路径
    upload_path = os.path.join(basepath, '/www/adamvue/src/images',
                               secure_filename(filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    f.save(upload_path)

    return ops_renderJSON(msg="附件上传成功")


@member_page.route('/postedu', methods=['GET', 'POST'])
def postedu():
    type = request.json.get('type')  # 更新/新增
    education = request.json.get('education')
    educationtype = request.json.get('educationtype')
    educationsn = request.json.get('educationsn')
    degreesn = request.json.get('degreesn')

    userid = request.json.get('userid')
    name = request.json.get('name')
    stime = request.json.get('stime')
    etime = request.json.get('etime')

    major = request.json.get('major')
    degree = request.json.get('degree')

    postername = request.json.get('postername')

    if postername:
        user = User.query.filter_by(id=userid).first()
        username = user.name
        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)

        if type == 1:
            id = request.json.get('id')
            useredu = UserEduexp.query.filter_by(id=id).first()
            useredu.name = name
            useredu.userid = userid
            if stime:
                useredu.stime = stime
            else:
                useredu.stime = "2000-1-1"
            if stime:
                useredu.etime = etime
            else:
                useredu.etime = "2000-1-1"
            useredu.major = major
            useredu.degree = degree
            useredu.education = education
            useredu.educationtype = educationtype
            useredu.educationsn = educationsn
            useredu.degreesn = degreesn
            useredu.updated_time = getCurrentTime()
            db.session.commit()
            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】修改一条教育经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "教育经历更新成功", "id": id}, ensure_ascii=False)
        else:
            useredu = UserEduexp()
            useredu.name = name
            useredu.userid = userid
            if stime:
                useredu.stime = stime
            else:
                useredu.stime = "2000-1-1"
            if stime:
                useredu.etime = etime
            else:
                useredu.etime = "2000-1-1"
            useredu.major = major
            useredu.degree = degree
            useredu.education = education
            useredu.educationtype = educationtype
            useredu.educationsn = educationsn
            useredu.degreesn = degreesn
            useredu.created_time = getCurrentTime()
            db.session.add(useredu)
            db.session.commit()
            id = useredu.id

            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】新增一条教育经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "教育经历添加成功", "id": id}, ensure_ascii=False)
    else:

        if type == 1:
            id = request.json.get('id')
            useredu = UserEduexp.query.filter_by(id=id).first()
            useredu.name = name
            useredu.userid = userid
            if stime:
                useredu.stime = stime
            else:
                useredu.stime = "2000-1-1"
            if stime:
                useredu.etime = etime
            else:
                useredu.etime = "2000-1-1"
            useredu.major = major
            useredu.degree = degree
            useredu.education = education
            useredu.educationtype = educationtype
            useredu.educationsn = educationsn
            useredu.degreesn = degreesn
            useredu.updated_time = getCurrentTime()
            db.session.commit()
            return json.dumps({"msg": "教育经历更新成功", "id": id}, ensure_ascii=False)
        else:
            useredu = UserEduexp()
            useredu.name = name
            useredu.userid = userid
            if stime:
                useredu.stime = stime
            else:
                useredu.stime = "2000-1-1"
            if stime:
                useredu.etime = etime
            else:
                useredu.etime = "2000-1-1"
            useredu.major = major
            useredu.degree = degree
            useredu.education = education
            useredu.educationtype = educationtype
            useredu.educationsn = educationsn
            useredu.degreesn = degreesn
            useredu.created_time = getCurrentTime()
            db.session.add(useredu)
            db.session.flush()
            db.session.commit()
            id = useredu.id
            return json.dumps({"msg": "教育经历添加成功", "id": id}, ensure_ascii=False)


@member_page.route('/postwork', methods=['GET', 'POST'])
def postwork():
    type = request.json.get('type')
    userid = request.json.get('userid')
    name = request.json.get('name')

    stime = request.json.get('stime')
    etime = request.json.get('etime')

    post = request.json.get('post')

    postername = request.json.get('postername')
    if postername:
        user = User.query.filter_by(id=userid).first()
        username = user.name
        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)

        if type == 1:
            id = request.json.get('id')
            userwork = UserWorkexp.query.filter_by(id=id).first()
            userwork.name = name
            userwork.userid = userid
            if stime:
                userwork.stime = stime
            else:
                userwork.stime = "2000-1-1"
            if etime:
                userwork.etime = etime
            else:
                userwork.etime = "1000-1-1"
            userwork.post = post
            userwork.updated_time = getCurrentTime()
            db.session.commit()
            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】修改一条工作经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "工作经历更新成功", "id": id}, ensure_ascii=False)
        else:
            userwork = UserWorkexp()
            userwork.name = name
            userwork.userid = userid
            if stime:
                userwork.stime = stime
            else:
                userwork.stime = "2000-1-1"
            if etime:
                userwork.etime = etime
            else:
                userwork.etime = "1000-1-1"
            userwork.post = post
            userwork.created_time = getCurrentTime()
            db.session.add(userwork)
            db.session.commit()
            id = userwork.id
            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】新增一条工作经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "工作经历添加成功", "id": id},
                              ensure_ascii=False)
    else:
        if type == 1:
            id = request.json.get('id')
            userwork = UserWorkexp.query.filter_by(id=id).first()
            userwork.name = name
            userwork.userid = userid
            if stime:
                userwork.stime = stime
            else:
                userwork.stime = "2000-1-1"
            if etime:
                userwork.etime = etime
            else:
                userwork.etime = "1000-1-1"
            userwork.post = post
            userwork.updated_time = getCurrentTime()
            db.session.commit()
            return json.dumps({"msg": "工作经历更新成功", "id": id}, ensure_ascii=False)
        else:
            userwork = UserWorkexp()
            userwork.name = name
            userwork.userid = userid
            if stime:
                userwork.stime = stime
            else:
                userwork.stime = "2000-1-1"
            if etime:
                userwork.etime = etime
            else:
                userwork.etime = "1000-1-1"
            userwork.post = post
            userwork.created_time = getCurrentTime()
            db.session.add(userwork)
            db.session.flush()
            db.session.commit()
            id = userwork.id
            return json.dumps({"msg": "工作经历添加成功", "id": id},
                              ensure_ascii=False)


@member_page.route('/postfamily', methods=['GET', 'POST'])
def postfamily():
    type = request.json.get('type')
    userid = request.json.get('userid')
    relationship = request.json.get('relationship')
    name = request.json.get('name')

    company = request.json.get('company')
    mobile = request.json.get('mobile')

    post = request.json.get('post')

    postername = request.json.get('postername')
    if postername:
        user = User.query.filter_by(id=userid).first()
        username = user.name
        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)

        if type == 1:
            id = request.json.get('id')
            userfamily = UserFamily.query.filter_by(id=id).first()
            userfamily.relationship = relationship
            userfamily.userid = userid
            userfamily.company = company
            userfamily.mobile = mobile
            userfamily.post = post
            userfamily.name = name
            userfamily.updated_time = getCurrentTime()
            db.session.commit()
            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】修改一条工作经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "家庭成员更新成功", "id": id}, ensure_ascii=False)
        else:
            userfamily = UserFamily()
            userfamily.relationship = relationship
            userfamily.userid = userid
            userfamily.company = company
            userfamily.mobile = mobile
            userfamily.post = post
            userfamily.name = name
            userfamily.created_time = getCurrentTime()
            db.session.add(userfamily)
            db.session.commit()
            id = userfamily.id
            msg = {
                "msgtype": "text",
                "text": {
                    "content": "操作员【" + postername + "】已对员工【" + username + "】新增一条工作经历"
                }
            }
            postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
            return json.dumps({"msg": "家庭成员添加成功", "id": id},
                              ensure_ascii=False)
    else:
        if type == 1:
            id = request.json.get('id')
            userfamily = UserFamily.query.filter_by(id=id).first()
            userfamily.relationship = relationship
            userfamily.userid = userid
            userfamily.company = company
            userfamily.mobile = mobile
            userfamily.post = post
            userfamily.name = name
            userfamily.updated_time = getCurrentTime()
            db.session.commit()
            return json.dumps({"msg": "家庭成员更新成功", "id": id}, ensure_ascii=False)
        else:
            userfamily = UserFamily()
            userfamily.relationship = relationship
            userfamily.userid = userid
            userfamily.company = company
            userfamily.mobile = mobile
            userfamily.post = post
            userfamily.name = name
            userfamily.created_time = getCurrentTime()
            db.session.add(userfamily)
            db.session.commit()
            id = userfamily.id
            return json.dumps({"msg": "家庭成员添加成功", "id": id},
                              ensure_ascii=False)


@member_page.route('/postcommission', methods=['GET', 'POST'])
def postcommission():
    type = request.json.get('type')  # 更新/新增
    userid = request.json.get('userid')
    stime = request.json.get('stime')
    etime = request.json.get('etime')
    post = request.json.get('post')
    sn = request.json.get('sn')
    content = request.json.get('content')

    if type == 1:
        id = request.json.get('id')
        Commission = UserCommission.query.filter_by(id=id).first()
        Commission.stime = stime
        Commission.userid = userid
        Commission.etime = etime
        Commission.post = post
        Commission.sn = sn
        Commission.content = content
        Commission.updated_time = getCurrentTime()
        db.session.commit()
        return json.dumps({"msg": "更新成功", "id": id}, ensure_ascii=False)
    else:
        Commission = UserCommission()
        Commission.stime = stime
        Commission.userid = userid
        Commission.etime = etime
        Commission.post = post
        Commission.sn = sn
        Commission.content = content
        Commission.created_time = getCurrentTime()
        db.session.add(Commission)
        db.session.flush()
        db.session.commit()
        id = Commission.id
        return json.dumps({"msg": "添加成功", "id": id}, ensure_ascii=False)


@member_page.route('/deleteedu', methods=['GET', 'POST'])
def deleteedu():
    id = request.json.get('id')
    postername = request.json.get('postername')

    if postername:
        useredu = UserEduexp.query.filter_by(id=id).delete()
        db.session.commit()

        userid = request.json.get('userid')
        user = User.query.filter_by(id=userid).first()
        username = user.name
        postername = request.json.get('postername')

        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)
        msg = {
            "msgtype": "text",
            "text": {
                "content": "操作员【" + postername + "】已对员工【" + username + "】删除一条教育经历"
            }
        }
        postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
        return json.dumps({"msg": "教育经历删除成功"}, ensure_ascii=False)
    else:
        useredu = UserEduexp.query.filter_by(id=id).delete()
        db.session.commit()
        return json.dumps({"msg": "教育经历删除成功"}, ensure_ascii=False)


@member_page.route('/deletework', methods=['GET', 'POST'])
def deletework():
    id = request.json.get('id')
    postername = request.json.get('postername')
    if postername:
        userwork = UserWorkexp.query.filter_by(id=id).delete()

        userid = request.json.get('userid')
        user = User.query.filter_by(id=userid).first()
        username = user.name

        db.session.commit()

        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)
        msg = {
            "msgtype": "text",
            "text": {
                "content": "操作员【" + postername + "】已对员工【" + username + "】删除一条工作经历"
            }
        }

        postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
        return json.dumps({"msg": "工作经历删除成功"}, ensure_ascii=False)
    else:
        userwork = UserWorkexp.query.filter_by(id=id).delete()
        db.session.commit()
        return json.dumps({"msg": "工作经历删除成功"}, ensure_ascii=False)


@member_page.route('/deletefamily', methods=['GET', 'POST'])
def deletefamily():
    id = request.json.get('id')
    postername = request.json.get('postername')
    if postername:
        userfamily = UserFamily.query.filter_by(id=id).delete()

        userid = request.json.get('userid')
        user = User.query.filter_by(id=userid).first()
        username = user.name

        db.session.commit()

        rolelist = client.role.simplelist(role_hr["人事经理"])
        userdict = rolelist['list']['emp_simple_list']
        userlist = []
        for i in userdict:
            temp = i["userid"]
            userlist.append(temp)
        msg = {
            "msgtype": "text",
            "text": {
                "content": "操作员【" + postername + "】已对员工【" + username + "】删除一条工作经历"
            }
        }

        postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)
        return json.dumps({"msg": "工作经历删除成功"}, ensure_ascii=False)
    else:
        userfamily = UserFamily.query.filter_by(id=id).delete()
        db.session.commit()
        return json.dumps({"msg": "工作经历删除成功"}, ensure_ascii=False)


@member_page.route('/deletecommission', methods=['GET', 'POST'])
def deletecommission():
    id = request.json.get('id')
    useredu = UserCommission.query.filter_by(id=id).delete()
    db.session.commit()
    return json.dumps({"msg": "删除成功"}, ensure_ascii=False)


@member_page.route('/updatauserinfo', methods=['GET', 'POST'])
def updatauserinfo():
    type = request.json.get('type')
    newdata = request.json.get('newdata')
    del newdata['age']
    name = request.json.get('name')
    id = newdata["id"]
    user = User.query.filter_by(id=id).first()
    olddata = queryToDict(user)

    if type == 1:
        keymap = Keymap.query.all()
        key = queryToDict(keymap)

        updata = {}
        for i in newdata.keys():
            if olddata[i] != newdata[i]:
                updata[i] = newdata[i]
        list = []
        for i in range(0, len(key)):
            for k in updata.keys():
                if key[i]['key'] == k:
                    temp = dict(key=key[i]['name'], value="由【" + str(olddata[k]) + "】变为【" + str(updata[k]) + "】")
                    list.append(temp)

    # if type == 1:
    #     user.contract_start = newdata['contract_start']
    #     user.contract_end = newdata['contract_end']
    #     user.contract_type = newdata['contract_type']
    #     user.employdate = newdata['employdate']
    dingtalkdeplist = request.json.get('dingtalkdeplist')
    user.dingtalkdepid = str(dingtalkdeplist).replace('[', '').replace(']', '').replace(' ', '').replace("'", "")

    user.keyinfo = newdata['keyinfo']
    user.depid = newdata['depid']
    user.name = newdata['name']
    user.sex = newdata['sex']
    user.idcardnum = newdata['idcardnum']
    user.idcardaddress = newdata['idcardaddress']
    user.address = newdata['address']
    user.nation = newdata['nation']
    user.marry = newdata['marry']
    user.jiguan = newdata['jiguan']
    user.mobile = newdata['mobile']
    user.email = newdata['email']
    user.title = newdata['title']
    user.pq = newdata['pq']
    user.hobby = newdata['hobby']
    user.blood = newdata['blood']
    user.tall = newdata['tall']
    user.role = newdata['role']
    user.hrrange = newdata['hrrange']
    if newdata['workdate'] != '':
        user.workdate = newdata['workdate']
    user.ec = newdata['ec']
    user.ecname = newdata['ecname']
    user.ecmobile = newdata['ecmobile']
    user.depid = newdata['depid']
    user.post = newdata['post']
    user.depid = newdata['depid']
    user.political = newdata['political']

    if newdata['employdate'] != '':
        user.employdate = newdata['employdate']
    if newdata['inductiondate'] != '':
        user.inductiondate = newdata['inductiondate']
    if newdata['contract_start'] != '':
        user.contract_start = newdata['contract_start']
    if newdata['contract_end'] != '':
        user.contract_end = newdata['contract_end']
    user.contract_long = newdata['contract_long']
    user.contract_body = newdata['contract_body']
    user.contract_type = newdata['contract_type']
    user.workplace = newdata['workplace']
    user.isss = newdata['isss']
    user.postclass = newdata['postclass']
    user.posttype = newdata['posttype']
    if newdata['interviewdate'] != '':
        user.interviewdate = newdata['interviewdate']
    # user.updated_time = getCurrentTime()

    db.session.commit()
    # if type == 1:
    #     rolelist = client.role.simplelist(role_hr["人事经理"])
    #     userdict = rolelist['list']['emp_simple_list']
    #     userlist = []
    #     for i in userdict:
    #         temp = i["userid"]
    #         userlist.append(temp)
    #     msg2 = {
    #         "msgtype": "text",
    #         "text": {
    #             "content": "操作员【" + name + "】已对员工【" + newdata['name'] + "】的资料进行修改，具体内容为：" + str(list)
    #         }
    #     }
    #
    #     msg = {
    #         "msgtype": "oa",
    #         "oa": {
    #             "head": {
    #                 "bgcolor": "FFBBBBBB",
    #                 "text": "员工信息修改通知"
    #             },
    #             "body": {
    #                 # "title": "员工信息修改",
    #                 "form": list,
    #                 "content": "操作员【" + name + "】已对员工【" + newdata['name'] + "】的资料进行修改",
    #
    #             }
    #         }
    #     }
    #     postinfo = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=userlist)

    return json.dumps("人员信息更新成功", ensure_ascii=False)


@member_page.route('/createuserinfo', methods=['GET', 'POST'])
def createuserinfo():
    newdata = request.json.get('newdata')
    userid = User.query.filter(User.id <= 20000).order_by(User.id.desc()).first()
    newid = int(userid.id) + 1

    user = User()
    user.name = newdata['name']
    user.id = newid
    user.role = "用户"
    user.status = 2
    user.mobile = newdata['mobile']
    user.jiguan = newdata['jiguan']
    user.title = newdata['title']
    user.pq = newdata['pq']
    user.ec = newdata['ec']
    user.ecname = newdata['ecname']
    user.ecmobile = newdata['ecmobile']
    user.email = newdata['email']
    user.idcardnum = newdata['idcardnum']
    user.post = newdata['post']
    user.hobby = newdata['hobby']
    user.marry = newdata['marry']
    user.nation = newdata['nation']
    user.salary = newdata['salary']
    user.address = newdata['address']
    user.sex = newdata['sex']
    user.political = newdata['political']
    user.blood = newdata['blood']
    user.tall = newdata['tall']
    user.depid = newdata['depid']
    user.role = 1
    user.dingtalkdepid = newdata['depid']
    user.interviewdate = newdata['interviewdate']
    user.created_time = getCurrentTime()
    db.session.add(user)
    db.session.commit()

    return json.dumps(newid, ensure_ascii=False)


@member_page.route('/updatauserinfo2', methods=['GET', 'POST'])
def updatauserinfo2():
    id = request.json.get('id')
    newdata = request.json.get('newdata')
    userid = request.json.get('userid')
    user = User.query.filter_by(id=id).first()

    if request.json.get('userid'):
        user.userid = request.json.get('userid')
        user.userid = userid

    user.name = newdata['name']
    user.sex = newdata['sex']
    user.idcardnum = newdata['idcardnum']
    user.idcardaddress = newdata['idcardaddress']

    user.address = newdata['address']
    user.nation = newdata['nation']
    user.marry = newdata['marry']
    user.political = newdata['political']
    user.jiguan = newdata['jiguan']
    user.mobile = newdata['mobile']
    user.email = newdata['email']
    user.title = newdata['title']
    user.pq = newdata['pq']
    user.hobby = newdata['hobby']
    user.blood = newdata['blood']
    user.tall = newdata['tall']
    user.weight = newdata['weight']
    if newdata['workdate'] != '':
        user.workdate = newdata['workdate']
    user.ec = newdata['ec']
    user.ecname = newdata['ecname']
    user.ecmobile = newdata['ecmobile']
    user.depid = newdata['depid']
    user.post = newdata['post']
    user.depid = newdata['depid']
    if newdata['employdate'] != '':
        user.employdate = newdata['employdate']
    if newdata['inductiondate'] != '':
        user.inductiondate = newdata['inductiondate']
    if newdata['contract_start'] != '':
        user.contract_start = newdata['contract_start']
    if newdata['contract_end'] != '':
        user.contract_end = newdata['contract_end']
    user.contract_long = newdata['contract_long']
    user.contract_body = newdata['contract_body']
    user.contract_type = newdata['contract_type']
    user.workplace = newdata['workplace']
    user.isss = newdata['isss']
    user.posttype = newdata['posttype']
    user.postclass = newdata['postclass']

    user.updated_time = getCurrentTime()
    db.session.commit()

    return json.dumps("666", ensure_ascii=False)


@member_page.route('/postuserid', methods=['GET', 'POST'])
def postuserid():
    userid = request.json.get('userid')

    user = User.query.filter_by(id=userid).first()
    user.userid = userid
    db.session.commit()
    return json.dumps("已获取新员工信息", ensure_ascii=False)


# ----------------------------------用户信息维护----------------------------------------

# ----------------------------------职位维护-----------------------------------------------

@member_page.route('/searchpost', methods=['GET', 'POST'])
def searchpost():
    name = request.json.get('search')
    member = UserPost.query.filter(UserPost.name.like('%' + name + '%')).all()
    rts = []
    for item in member:
        temp = dict(label=item.name, value=item.name, key=item.id)
        rts.append(temp)
    return json.dumps(rts, ensure_ascii=False)


@member_page.route('/postpost', methods=['GET', 'POST'])
def postpost():
    type = request.json.get('type')
    post = request.json.get('post')

    if type == 1:
        id = request.json.get('id')
        postq = UserPost.query.filter_by(id=id).first()

        postq.name = post
        # postq.updated_time = getCurrentTime()
        db.session.commit()
        return json.dumps({"msg": "职位信息修改成功", "id": id}, ensure_ascii=False)
    else:
        postq = UserPost()

        postq.name = post
        # postq.created_time = getCurrentTime()
        db.session.add(postq)
        db.session.flush()
        db.session.commit()
        id = postq.id
        return json.dumps({"msg": "职位信息添加成功", "id": id},
                          ensure_ascii=False)


@member_page.route('/deletepost', methods=['GET', 'POST'])
def deletepost():
    id = request.json.get('id')
    post = UserPost.query.filter_by(id=id).delete()
    db.session.commit()
    return json.dumps({"msg": "职位信息删除成功"}, ensure_ascii=False)


@member_page.route('/syninfotodingtalk', methods=['GET', 'POST'])
def syninfotodingtalk():
    user = User.query.filter_by(id=739).first()
    workdate = user.workdate
    # content = {"userid": user.userid,"extension": {
    #     "首次参加工作时间": workdate,
    # }, }
    # content = {"agentid": "1784691312", }

    #     content1=  {
    #   "agentid": "1784691312",
    #   "param": {
    #     "groups": [
    #       {
    #         "group_id": "sys03",
    #         "sections": [
    #           {
    #             "old_index": 0,
    #             "section": [
    #               {
    #                 "field_code": "sys03-highestEdu",
    #                 "value": "1"
    #               },
    #               {
    #                 "field_code": "sys03-graduateSchool",
    #                 "value": "测试大学"
    #               },
    #               {
    #                 "field_code": "sys03-graduationTime",
    #                 "value": "2020-09-01"
    #               }
    #             ]
    #           },
    #           {
    #             "old_index": 1,
    #             "section": [
    #               {
    #                 "field_code": "sys03-highestEdu",
    #                 "value": "2"
    #               },
    #               {
    #                 "field_code": "sys03-graduateSchool",
    #                 "value": "测试附中"
    #               },
    #               {
    #                 "field_code": "sys03-graduationTime",
    #                 "value": "2016-09-01"
    #               }
    #             ]
    #           },
    #           {
    #             "old_index": 2,
    #             "section": [
    #               {
    #                 "field_code": "sys03-highestEdu",
    #                 "value": "3"
    #               },
    #               {
    #                 "field_code": "sys03-graduateSchool",
    #                 "value": "测试附小"
    #               },
    #               {
    #                 "field_code": "sys03-graduationTime",
    #                 "value": "2010-09-01"
    #               }
    #             ]
    #           }
    #         ]
    #       }
    #     ],
    #     "userid": user.userid
    #   }
    # }

    content = {
        "agentid": "1784691312",
        "param": {
            "groups": [
                {
                    "group_id": "sys02",
                    "sections": [
                        {
                            "section": [
                                {
                                    "field_code": "sys02-joinWorkingTime",
                                    "value": "2013-08-01"
                                },
                            ]
                        },
                    ]
                }
            ],
            "userid": user.userid
        },

    }

    url = "https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/v2/update"
    # url = "https://oapi.dingtalk.com/topapi/v2/user/update"
    a = dingtalkpost(url=url, content=content)

    return json.dumps({"msg": a}, ensure_ascii=False)


# ----------------------------------职位维护-----------------------------------------------

# ----------------------------------同步-----------------------------------------------

@member_page.route('/getsystem', methods=['GET', 'POST'])
def getsystem():
    id = request.json.get("id")
    user = User.query.filter_by(userid=id).first()
    role = "99,1,2,3,4,5"
    rolelist = role.split(",")
    rts = []

    for i in rolelist:
        weight = UserWeight.query.all()

        for q in weight:
            a = q.role
            b = a.split(",")
            if i in b:
                temp = dict(url=q.url, imgurl=q.imgurl)
                rts.append(temp)
    # 去重
    result = []
    for i in rts:
        result = unduplicate(result, i)

    return json.dumps(result, ensure_ascii=False)


@member_page.route('/sendcollect', methods=['GET', 'POST'])
def sendcollect():
    # list = [857, 739]
    renyuan = User.query.filter(
        User.id == 856).all()

    # renyuan = User.query.filter(
    #     or_(User.status == 4, User.status == 1)).filter(User.id >= 49999).all()

    userlist = []
    for i in renyuan:
        userlist.append(i.userid)

    for i in userlist:
        user = User.query.filter_by(userid=i).first()
        id = str(user.id)
        name = user.name

        base_url = 'http://101.132.227.54:88/workusercollect?id=' + id
        encodeurl = urllib.parse.quote(base_url)

        dingtalkurl = "dingtalk://dingtalkclient/action/openapp?corpid=ding5b2aa85601c5363fffe93478753d9884&container_type=work_platform&app_id=0_1784691312&redirect_type=jump&redirect_url=" + encodeurl
        normalurl = "dingtalk://dingtalkclient/page/link?url=" + encodeurl + "&pc_slide=true"

        msg = {
            "msgtype": "action_card",
            "action_card": {
                "title": "在职人员信息完善",
                "markdown": "![](http://upload.guanzhuoran.cn/information.png)   \n   #### 工号:" + id + "   姓名:" + name,
                "btn_orientation": "1",
                "btn_json_list": [
                    # {
                    #     "title": "完善信息(PC)",
                    #     "action_url": dingtalkurl,
                    # },
                    {
                        "title": "完善信息",
                        "action_url": normalurl,
                    },

                ]
            }
        }

        a = client.message.asyncsend_v2(msg_body=msg, agent_id=AgentId, userid_list=i.split())

    return json.dumps("成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


@member_page.route('/writedep', methods=['GET', 'POST'])
def writedep():
    type = request.args.get('type')

    user = User.query.filter(
        or_(User.status == 4, User.status == 1)).all()
    # 同步dingtalkdepid
    if type == "1":
        for i in user:
            temp = client.user.get(userid=i.userid)
            user2 = User.query.filter_by(userid=i.userid).first()
            user2.dingtalkdepid = str(temp.department).replace('[', '').replace(']', '').replace(' ', '')

            # print(str(temp.department).replace('[','').replace(']',''))
            db.session.commit()

        return json.dumps("成功推送", indent=4, sort_keys=True,
                          default=str,
                          ensure_ascii=False)
    # 同步主部门
    if type == "2":
        for i in user:
            temp = client.user.get(userid=i.userid)
            user2 = User.query.filter_by(userid=i.userid).first()

            user2.depid = temp.department[0]

            # user2.dingtalkdepid = str(temp.department).replace('[', '').replace(']', '').replace(' ', '')

            db.session.commit()

        return json.dumps("成功推送", indent=4, sort_keys=True,
                          default=str,
                          ensure_ascii=False)


@member_page.route('/writemobile', methods=['GET', 'POST'])
def writemobile():
    user = User.query.filter(
        or_(User.status == 4, User.status == 1)).all()
    for i in user:
        temp = client.user.get(userid=i.userid)
        user2 = User.query.filter_by(userid=i.userid).first()

        user2.dingtalkmobile = temp.mobile

        # user2.dingtalkdepid= str(temp.department).replace('[','').replace(']','').replace(' ','')
        #
        # print(str(temp.department).replace('[','').replace(']',''))
        print(i.id)
        db.session.commit()

    return json.dumps("成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


def adddep(i):
    ifdep = Department.query.filter_by(id=i.id).first()
    content = {
        "language": "zh_CN",
        "dept_id": int(i.id)
    }
    url = "https://oapi.dingtalk.com/topapi/v2/department/get"
    a = dingtalkpost(url=url, content=content)
    if 'dept_manager_userid_list' in a['result']:
        user = User.query.filter_by(userid=a['result']['dept_manager_userid_list'][0]).first()
        if user:
            userid = user.id
        else:
            userid = 1
    else:
        userid = 0
    if ifdep:
        ifdep.name = i.name
        ifdep.id = i.id
        ifdep.pid = i.parentid
        ifdep.mannger = userid
        db.session.commit()
    else:
        dep = Department()
        dep.name = i.name
        dep.id = i.id
        dep.pid = i.parentid
        dep.mannger = userid
        db.session.add(dep)
        db.session.commit()

def findlowdep(department):
    for i in department:
        adddep(i)
        dep = client.department.list(_id=i.id)
        if dep:
            findlowdep(dep)



@member_page.route('/sysdep', methods=['GET', 'POST'])
def sysdep():
    department = client.department.list()
    findlowdep(department)
    return json.dumps("成功推送", indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)


# ----------------------------------同步-----------------------------------------------
# 查找组织
def Org_Find_Dep(depid):
    dep = Department.query.filter_by(pid=depid).all()
    return dep


# 查找用户
def Org_Find_user(userid):
    user = User.query.filter_by(depid=userid).filter(
        or_(User.status == 4, User.status == 1)).order_by(User.id).all()
    return user


# 组装数据
def Pack_Tree_Dict(obejct, type):
    if type == 0:
        manger = User.query.filter_by(id=obejct.mannger).order_by(User.id).first()
        if manger:
            tree = {"type": "dep", "id": obejct.id, "label": obejct.name, "sonlabel": "负责人：" + manger.name,
                    "children": [], "url": "http://101.132.227.54:8008/images/"+str(manger.id)+".png", "icon": "el-icon-s-home"}
        else:
            tree = {"type": "dep", "id": obejct.id, "label": obejct.name, "sonlabel": "暂无负责人", "children": [],
                    "url": "http://101.132.227.54:8008/images/omh.png", "icon": "el-icon-s-home"}
    else:
        tree = {"type": "user", "id": obejct.id, "label": obejct.name, "sonlabel": obejct.department.name,
                "url": "http://101.132.227.54:8008/images/"+str(obejct.id)+".png", "icon": "el-icon-user-solid"}
    return tree


# 递归添加子项数据
def Make_Tree(dep, higher_dep_object, higher_dep_dict):
    if dep:
        for item_dep in dep:
            dep_dict = Pack_Tree_Dict(item_dep, 0)
            higher_dep_dict["children"].append(dep_dict)
            lowdep = Org_Find_Dep(item_dep.id)
            Make_Tree(lowdep, item_dep, dep_dict)
    else:
        user = Org_Find_user(higher_dep_object.id)
        if user:
            for item_user in user:
                # 剔除部门负责人
                if item_user.id != higher_dep_object.mannger:
                    user_dict = Pack_Tree_Dict(item_user, 1)
                    higher_dep_dict["children"].append(user_dict)


@member_page.route('/make_org_tree_data', methods=['GET', 'POST'])
def make_org_tree_data():
    selecarr = request.json.get('selecarr')
    datalist = []
    department = Department.query.filter_by(id=selecarr[0]).first()
    dep1 = Org_Find_Dep(department.id)
    for itemdep1 in dep1:
        item1dep = Pack_Tree_Dict(itemdep1, 0)
        dep2 = Org_Find_Dep(itemdep1.id)
        # 递归添加子项数据
        Make_Tree(dep2, itemdep1, item1dep)
        datalist.append(item1dep)

    if datalist == []:
        user = Org_Find_user(department.id)
        if user:
            for item_user in user:
                # 剔除部门负责人
                if item_user.id != department.mannger:
                    user_dict = Pack_Tree_Dict(item_user, 1)
                    datalist.append(user_dict)

    manger = User.query.filter_by(id=department.mannger).order_by(User.id).first()
    if manger:
        finaldate = {"type": "dep", "id": department.id, "label": department.name, "sonlabel": "负责人：" + manger.name,
                     "children": datalist,
                     "url": "http://101.132.227.54:8008/images/"+str(manger.id)+".png", "icon": "el-icon-s-home"}
    else:
        finaldate = {"type": "dep", "id": department.id, "label": department.name, "sonlabel": "暂无负责人",
                     "children": datalist,
                     "url": "http://101.132.227.54:8008/images/omh.png", "icon": "el-icon-s-home"}

    # finaldate= {"id":department.id,"label":department.name,"children":datalist,"url":"http://101.132.227.54:8008/images/739.png"}

    return json.dumps(finaldate, indent=4, sort_keys=True,
                      default=str,
                      ensure_ascii=False)
